package fightplan.persistence;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.Region;

import fightplan.business.Category;
import fightplan.business.Plan;
import fightplan.business.Winner;

public class WinnerReport {

	public static void createReport(List<Category> categories, File file) throws IOException {

		HSSFWorkbook wb = new HSSFWorkbook();
		HSSFSheet sheet = wb.createSheet("Rangliste");

		HSSFFont font = wb.createFont();
		font.setFontHeightInPoints((short) 14);
		font.setFontName("Arial");
		// font.setItalic(true);
		// font.setStrikeout(true);

		// Fonts are set into a style so create a new one to use.
		HSSFCellStyle style = wb.createCellStyle();
		style.setFont(font);

		int rowCount = -1;

		for (Category category : categories) {
			HSSFRow row = sheet.createRow(++rowCount);
			HSSFCell cell = row.createCell((short) 0);
			cell.setCellValue(category.getDescription());
			cell.setCellStyle(style);
			sheet.addMergedRegion(new Region(rowCount, (short) 0, rowCount, (short) 2));

			if (category.getPlan() != null) {
				Plan plan = category.getPlan();
				for (Winner winner : plan.getWinners()) {
					row = sheet.createRow(++rowCount);
					cell = row.createCell((short) 0);
					cell.setCellValue(winner.getRank());
					cell = row.createCell((short) 1);
					if (winner.getFighterHolder().getFighter() != null) {
						cell.setCellValue(winner.getFighterHolder().getFighter().getName());
						if (winner.getFighterHolder().getFighter().getDojo() != null) {
							cell = row.createCell((short) 2);
							cell.setCellValue(winner.getFighterHolder().getFighter().getDojo().getName());
						}
					} else {
						cell.setCellValue("-");
					}
				}
			} else {
				row = sheet.createRow(++rowCount);
				cell = row.createCell((short) 1);
				cell.setCellValue("Nicht durchgeführt.");
			}
		}

		sheet.setColumnWidth((short) 0, (short) 1000);
		sheet.setColumnWidth((short) 1, (short) 8000);
		sheet.setColumnWidth((short) 2, (short) 6000);

		FileOutputStream out = new FileOutputStream(file);
		wb.write(out);
		out.close();
	}

}
